<?php
/**
 * desc Created by wang.
 * User: wang
 * motto: 是时候为小时候吹过的牛而努力了!
 * Date: 2020/3/31 9:45
 */

namespace app\admin\controller;


use think\facade\View;
use app\admin\validate\Login as LoginValidate;
use app\admin\business\Manager as BusManager;

class Login extends AdminBase
{

    public function initialize()
    {
        //检测是否登录
        if ($this->isLogin()) {
            $this->redirect(url('/admin/index/index'));
        }
    }

    /**
     * 功能说明 登录页面
     * @author: wang
     * @Date: 2020/3/31 14:08
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return View::fetch('index');
    }

    /**
     * 功能说明 登录逻辑
     * @author: wang
     * @Date: 2020/3/31 15:11
     * @return \think\response\Json
     */
    public function login()
    {
        if($this->request->isAjax()){
            $username = $this->request->param('name', '', 'trim,htmlspecialchars');
            $password = $this->request->param('password', '', 'trim,htmlspecialchars');
            $data = [
                'username' => $username,
                'password' => $password,
            ];

            $LoginValidate = new LoginValidate();
            if (!$LoginValidate->scene('login')->check($data)) {
                return $this->show(config('status.error'), $LoginValidate->getError());
            }
            try {
                $result = BusManager::login($data);
            } catch (\Exception $e) {
                return $this->show(config('status.error'), $e->getMessage());
            }
            if($result){
                return $this->result(config('status.success'), '登录成功', '/admin/index/index');
            }
            return $this->show(config('status.success'), '登录失败');

        }

        return $this->show(config('status.error'), '非法请求!');
    }

}